package com.glowworms.core.util;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.glowworms.core.constant.WebConstant;

/**
 * 邮件发送工具类
 */
public abstract class MailUtils {

	/**
	 * 发送邮件
	 * 
	 * @param tos
	 * @param title
	 * @param content
	 * @return
	 */
	public static boolean sendSimpleMail(String from, String to, String title, String content) {
		return sendSimpleMails(from, new String[] { to }, title, content);
	}

	/**
	 * 发送邮件, 发送多人
	 * 
	 * @param tos
	 * @param title
	 * @param content
	 * @return
	 */
	public static boolean sendSimpleMails(String from, String[] tos, String title, String content) {
		JavaMailSender javaMailSenderImpl = getJavaMailSender(from);
		SimpleMailMessage mailMessage = new SimpleMailMessage();
		mailMessage.setFrom(from);
		mailMessage.setTo(tos);
		mailMessage.setSubject(title);
		mailMessage.setText(content);
		javaMailSenderImpl.send(mailMessage);
		return true;
	}

	/**
	 * 获取邮件发送器
	 * 
	 * @param from
	 * @return
	 */
	public static JavaMailSender getJavaMailSender(String from) {
		return null;
	}

	/**
	 * 富文本邮件
	 * 
	 * @param tos
	 * @param title
	 * @param content
	 * @return
	 */
	public static boolean sendHtmlMail(String from, String to, String title, String content, File[] attachs) {
		return sendHtmlMail(from, new String[] { to }, title, content, attachs);
	}

	/**
	 * 富文本邮件
	 * 
	 * @param from
	 * @param tos
	 * @param title
	 * @param content
	 * @param attachs
	 * @return
	 */
	public static boolean sendHtmlMail(String from, String[] tos, String title, String content, File[] attachs) {
		JavaMailSender javaMailSenderImpl = getJavaMailSender(from);
		MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
		try {
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, WebConstant.ENCODE);
			mimeMessageHelper.setTo(tos);
			mimeMessageHelper.setFrom(from);
			mimeMessageHelper.setSubject(title);
			mimeMessageHelper.setText(content, true);
			if (ObjectUtils.isNotNull(attachs)) {
				for (File file : attachs) {
					if (file.exists()) {
						FileSystemResource attachmentFile = new FileSystemResource(file);
						mimeMessageHelper.addAttachment(file.getName(), attachmentFile);
					}
				}
			}
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
	}
}
